<template>
  <a-modal
    :visible="visible"
    :title="title"
    :width="width"
    :maskClosable="maskClosable"
    :destroyOnClose="destroyOnClose"
    @cancel="handleCancel"
    @ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: labelSpan }"
      :wrapper-col="{ span: 24 - labelSpan }"
    >
      <template v-for="(item, index) in formItems" :key="index">
        <!-- 表单行布局 -->
        <template v-if="item.type === FormItemType.ROW">
          <a-row :gutter="(item as FormRowItem).gutter || 24">
            <template v-for="(child, _idx) in (item as FormRowItem).children" :key="`${index}-${_idx}`">
              <a-col 
                :span="child.span || 24" 
                :xs="child.xs" 
                :sm="child.sm" 
                :md="child.md" 
                :lg="child.lg" 
                :xl="child.xl"
              >
                <a-form-item
                  v-if="showFormItem(child)"
                  :label="child.label"
                  :name="child.field"
                  :help="child.help"
                >
                  <form-item-render
                    :type="child.type"
                    v-model:modelValue="formData[child.field as string]"
                    :placeholder="child.placeholder"
                    :options="child.options"
                    :tree-data="child.treeData"
                    :disabled="child.disabled"
                    :min="child.min"
                    :max="child.max"
                    :step="child.step"
                    :rows="child.rows"
                    :allow-clear="child.allowClear"
                    :mode="child.mode"
                    :field-names="child.fieldNames"
                    :slot-name="child.slotName"
                    :form-data="formData"
                    :props="child.props || {}"
                  />
                </a-form-item>
              </a-col>
            </template>
          </a-row>
        </template>
        
        <!-- 常规表单项 -->
        <template v-else>
          <a-form-item
            v-if="showFormItem(item as FormItemConfig)"
            :label="(item as FormItemConfig).label"
            :name="(item as FormItemConfig).field"
            :help="(item as FormItemConfig).help"
          >
            <form-item-render
              :type="(item as FormItemConfig).type"
              v-model:modelValue="formData[(item as FormItemConfig).field as string]"
              :placeholder="(item as FormItemConfig).placeholder"
              :options="(item as FormItemConfig).options"
              :tree-data="(item as FormItemConfig).treeData"
              :disabled="(item as FormItemConfig).disabled"
              :min="(item as FormItemConfig).min"
              :max="(item as FormItemConfig).max"
              :step="(item as FormItemConfig).step"
              :rows="(item as FormItemConfig).rows"
              :allow-clear="(item as FormItemConfig).allowClear"
              :mode="(item as FormItemConfig).mode"
              :field-names="(item as FormItemConfig).fieldNames"
              :slot-name="(item as FormItemConfig).slotName"
              :form-data="formData"
              :props="(item as FormItemConfig).props || {}"
            />
          </a-form-item>
        </template>
      </template>
    </a-form>

    <!-- 自定义表单内容插槽 -->
    <slot></slot>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, nextTick } from 'vue'
import FormItemRender from './FormItemRender.vue'
import type { FormItemConfig, FormRowItem } from '@/types/component/form'
import { FormItemType } from '@/types/component/form'
import type { Rule } from 'ant-design-vue/es/form'
import type { FormInstance } from 'ant-design-vue/es/form/Form'

defineOptions({
  name: 'BaseModal'
})

// Props定义
const props = withDefaults(defineProps<{
  visible: boolean
  title?: string
  width?: number | string
  labelSpan?: number
  maskClosable?: boolean
  destroyOnClose?: boolean
  formItems: Array<FormItemConfig | FormRowItem>
  rules?: Record<string, Rule[]>
  initialValues?: Record<string, any>
  record?: Record<string, any>
}>(), {
  visible: false,
  title: '表单',
  width: 700,
  labelSpan: 6,
  maskClosable: false,
  destroyOnClose: true,
  formItems: () => [],
  rules: () => ({}),
  initialValues: () => ({})
})

// Emits定义
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'cancel': []
  'submit': [formData: Record<string, any>]
  'success': []
}>()

const formRef = ref<FormInstance>()
const formData = reactive<Record<string, any>>({})

// 初始化表单数据
const initFormData = () => {
  // 清空之前的数据
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  // 设置初始值
  const initialData = { ...props.initialValues }
  
  // 如果有记录，合并记录数据
  if (props.record) {
    Object.assign(initialData, props.record)
  }
  
  // 设置表单项的默认值
  props.formItems.forEach(item => {
    if (item.type === FormItemType.ROW) {
      (item as FormRowItem).children.forEach(child => {
        if (child.field && initialData[child.field] === undefined && child.value !== undefined) {
          initialData[child.field] = child.value
        }
      })
    } else if ((item as FormItemConfig).field) {
      const field = (item as FormItemConfig).field as string
      if (initialData[field] === undefined && (item as FormItemConfig).value !== undefined) {
        initialData[field] = (item as FormItemConfig).value
      }
    }
  })
  
  // 将初始数据设置到表单数据中
  Object.assign(formData, initialData)
}

// 判断是否显示表单项
const showFormItem = (item: FormItemConfig) => {
  if (item.condition === undefined) return true
  if (typeof item.condition === 'boolean') return item.condition
  return item.condition(formData)
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  initFormData()
}

// 提交表单
const handleSubmit = () => {
  if (!formRef.value) return
  
  formRef.value.validate().then(() => {
    emit('submit', { ...formData })
  }).catch(err => {
    console.error('Validate failed:', err)
  })
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
  emit('cancel')
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    nextTick(() => {
      initFormData()
    })
  }
})

// 初始化
initFormData()

// 暴露方法供父组件使用
defineExpose({
  resetForm,
  formRef
})
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 16px;
}
</style> 